package com.feng.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.feng.model.AdminUser;
import com.feng.service.AdminUserService;
import com.feng.util.PageResult;
import com.feng.util.Search;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping(value = "/adminUser")
public class AdminUserAction {
	private static Logger log = LogManager.getLogger(AdminUserAction.class);

    @Resource(name = "adminUserService")
    private AdminUserService adminUserService;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public  PageResult<AdminUser> list(@RequestBody Search search) {
        PageResult<AdminUser> ret = null;
        try {
            ret = adminUserService.findByPage(search);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(),e);
        }
        return ret;
    }

    // 通过Id查账管理员
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public JSONObject findById(@PathVariable("id") Long id) {
        JSONObject ret = new JSONObject();
        boolean success = false;
        try {
            AdminUser adminUser = adminUserService.get(id);
            ret.put("data", adminUser);
            success = true;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        ret.put("success", success);
        return ret;
    }

    // 保存或更新
    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    public JSONObject saveOrUpdate(@RequestBody AdminUser adminUser,HttpSession session) {
        JSONObject ret = new JSONObject();
        boolean success = false;
        try {
            Long id = adminUser.getId();
            adminUserService.saveOrUpdate(adminUser);
  //          adminUser.setHeadpic(PicUtil.transfer( adminUser.getHeadpic(), UPLOAD_PATH_ADMIN));
            success = true;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        ret.put("success", success);
        return ret;
    }

    // 判断重复
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public JSONObject check(@RequestBody AdminUser adminUser) {
        JSONObject ret = new JSONObject();
        boolean success = false;
        try {
            ret = adminUserService.ckeck(adminUser);
            success = true;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        ret.put("success", success);
        return ret;
    }
    
    // 通过id删除
    @RequestMapping(value = "/del/{adminId}", method = RequestMethod.GET)
    public JSONObject delByClass(@PathVariable("adminId") final Long adminId,
            HttpSession session) {
        JSONObject ret = new JSONObject();
        boolean success = false;
        try {
        	AdminUser adminUser = adminUserService.get(adminId);
            adminUserService.del(adminId);
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getStackTrace());
        }
        ret.put("success", success);
        return ret;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JSONObject adminLogin(@RequestBody AdminUser admin,HttpSession session) {
        JSONObject ret = new JSONObject();
        boolean success = false;
        AdminUser user = null;
        try {
            user = adminUserService.findUserByAccount(admin.getAccount());
            if(user == null){
                ret.put("error","帐号不存在");
            }else if(!user.getPassword().equals(admin.getPassword())){
                ret.put("error","密码错误");
            }else{
                session.setAttribute("admin",user);
                String sessionId = session.getId();
                ServletContext applicationCtx = session.getServletContext();
                applicationCtx.setAttribute(user.getId().toString(), sessionId);
                ret.put("admin",user);
                success = true;
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            ret.put("error",e.getMessage());
        }
        ret.put("success", success);
        return ret;
    }

    @RequestMapping(value = "/logout")
    public ModelAndView logout(HttpSession session) {
        ModelAndView view = new ModelAndView();
        session.invalidate();
        view.setView(new RedirectView("/login.html", false));
        return view;
    }

    @RequestMapping(value = "/getUserbySession")
    public Object getUserbySession(HttpSession session) {
        AdminUser user = (AdminUser)session.getAttribute("admin");
        if(user!=null){
            JSONObject ret = (JSONObject)JSONObject.toJSON(user);
            SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
            filter.getExcludes().add("password");
            String jsonStr = JSON.toJSONString(ret, filter);
            return JSON.parse(jsonStr);
        }else{
            return user;
        }
    }

    @RequestMapping(value = "/findAllAdminUser")
    public List<AdminUser> findAllAdminUser(HttpSession session) {
        return adminUserService.findAllAdminUser();
    }

    @RequestMapping(value = "/changPwd")
    public JSONObject changPwd(HttpSession session,@RequestParam String password,@RequestParam String password1) {
        JSONObject ret = new JSONObject();
        AdminUser user = (AdminUser)session.getAttribute("admin");
        if(user == null){
            ret.put("success",false);
            ret.put("error","会话已失效，请重新登录！");
            return ret;
        }
        if(!user.getPassword().equals(password)){
            ret.put("success",false);
            ret.put("error","密码错误，请先确认！");
            return ret;
        }
        try {
            user.setPassword(password1);
            adminUserService.update(user);
            ret.put("success",true);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            ret.put("success", false);
            ret.put("error",e.getMessage());
        }
        session.invalidate();
        return ret;
    }
}
